package com.huashiai.videocall.signal.entity;

import com.corundumstudio.socketio.SocketIOClient;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: xchb
 * @date: 2021/4/26 11:08
 * @description:
 */
@Component
public class RoomContainer {

    // 房间对应的客户端id
    private static Map<String, List<SocketIOClient>> personMap = new ConcurrentHashMap<>();

    public static SocketIOClient selectByClientId(String to) {
        Iterator<String> iterator = personMap.keySet().iterator();
        while (iterator.hasNext()){
            String key = iterator.next();
            List<SocketIOClient> socketIOClients = personMap.get(key);
            if(socketIOClients==null || socketIOClients.size()<1){
                continue;
            }
            Iterator<SocketIOClient> iterator1 = socketIOClients.iterator();
            while (iterator1.hasNext()){
                SocketIOClient next = iterator1.next();
                String sessionId = String.valueOf(next.getSessionId());
                if(next!=null && to.equals(sessionId)){
                    return next;
                }
            }

        }
        return null;
    }

    public List<String> addPerson(String room, SocketIOClient client) {

        ArrayList otherPerson = new ArrayList();

        List<SocketIOClient> socketIOClients = personMap.get(room);
        if(socketIOClients==null){
            socketIOClients = new Vector<>(5);
        }else{
            socketIOClients.stream().forEach(e->{
                otherPerson.add(e.getSessionId());
            });
        }

        socketIOClients.add(client);
        personMap.put(room,socketIOClients);

        return otherPerson;
    }

    public void removePerson(SocketIOClient client) {
        Iterator<String> iterator = personMap.keySet().iterator();
        while (iterator.hasNext()){
            String key = iterator.next();
            List<SocketIOClient> socketIOClients = personMap.get(key);
            if(socketIOClients==null || socketIOClients.size()<1){
                continue;
            }
            Iterator<SocketIOClient> iterator1 = socketIOClients.iterator();
            while (iterator1.hasNext()){
                if(iterator1.next()==client){
                    iterator1.remove();
                    return;
                }
            }

        }
    }
}
